// Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

import { TurboModule, TurboModuleContext } from '@rnoh/react-native-openharmony/ts';
import { TM } from './generated/ts'
import window from '@ohos.window';
import image from '@ohos.multimedia.image';
import Logger from './Logger';

export class SplashScreen extends TurboModule implements TM.SplashScreen.Spec {
  static NAME = "SplashScreen"

  // 启动图片
  public static startWindowIcon;

  // 子窗口
  private static splashWindow;

  constructor(ctx: TurboModuleContext) {
    super(ctx)
  }

  /**
   * 显示启动屏
   *
   */
  public static async show(abilityContext: any,
                           windowStage: window.WindowStage,
                           iconResource: any,
                           backgroundColor: string,
                           pageUrl: string) {
    // 获取resourceManager资源管理
    const context = abilityContext;
    const resourceMgr = context.resourceManager
    // 获取rawfile文件夹下startIcon的ArrayBuffer
    const fileData = await resourceMgr.getMediaContent(iconResource)
    const buffer = fileData.buffer
    // 创建imageSource
    const imageSource = image.createImageSource(buffer)
    // 创建PixelMap
    const pixelMap = await imageSource.createPixelMap()
    SplashScreen.startWindowIcon = pixelMap;

    // 创建子窗口
    windowStage.createSubWindow("SplashScreenWindow", (err, data) => {
      if (err.code) {
        Logger.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err));
        return;
      }
      SplashScreen.splashWindow = data;

      // 设置子窗口全屏
      SplashScreen.splashWindow.setFullScreen(true);

      // 为子窗口加载对应的目标页面
      SplashScreen.splashWindow.setUIContent(pageUrl, (err) => {
        if (err.code) {
          Logger.error('Failed to load the content. Cause:' + JSON.stringify(err));
          return;
        }
        // 显示子窗口
        SplashScreen.splashWindow.showWindow((err) => {
          if (err.code) {
            Logger.error('Failed to show the window. Cause: ' + JSON.stringify(err));
            return;
          }
          Logger.debug('Succeeded in showing the window.');
        });
        SplashScreen.splashWindow.setWindowBackgroundColor(backgroundColor)
      });
    })
  }

  /**
   * 关闭启动屏
   */
  public hide() {
    // 销毁子窗口
    SplashScreen.splashWindow.destroyWindow((err) => {
      if (err.code) {
        Logger.error('Failed to destroy the window. Cause: ' + JSON.stringify(err));
        return;
      }
    });
  }
}
